interface Cache {
    set: (key: string | null, value: string | null) => void;
    get: (key: string | null) => string | null;
    setJSON: (key: string | null, jsonValue: any) => void;
    getJSON: (key: string | null) => any;
    remove: (key: string | null) => void;
}

const sessionCache: Cache = {
    set (key: string | null, value: string | null) {
        if (!sessionStorage) {
            return;
        }
        if (key != null && value != null) {
            sessionStorage.setItem(key, value);
        }
    },
    get (key: string | null): string | null {
        if (!sessionStorage) {
            return null;
        }
        if (key == null) {
            return null;
        }
        return sessionStorage.getItem(key);
    },
    setJSON (key: string | null, jsonValue: any) {
        if (jsonValue != null) {
            this.set(key, JSON.stringify(jsonValue));
        }
    },
    getJSON (key: string | null): any {
        const value = this.get(key);
        if (value != null) {
            return JSON.parse(value);
        }
        return null;
    },
    remove (key: string | null) {
        if (key != null) {
            sessionStorage.removeItem(key);
        }
    }
};

const localCache: Cache = {
    set (key: string | null, value: string | null) {
        if (!localStorage) {
            return;
        }
        if (key != null && value != null) {
            localStorage.setItem(key, value);
        }
    },
    get (key: string | null): string | null {
        if (!localStorage) {
            return null;
        }
        if (key == null) {
            return null;
        }
        return localStorage.getItem(key);
    },
    setJSON (key: string | null, jsonValue: any) {
        if (jsonValue != null) {
            this.set(key, JSON.stringify(jsonValue));
        }
    },
    getJSON (key: string | null): any {
        const value = this.get(key);
        if (value != null) {
            return JSON.parse(value);
        }
        return null;
    },
    remove (key: string | null) {
        if (key != null) {
            localStorage.removeItem(key);
        }
    }
};

export default {
    /**
     * 会话级缓存
     */
    session: sessionCache,
    /**
     * 本地缓存
     */
    local: localCache
};